
"""
@file dicom.py
@docs 对dicom进行基本处理，提取信息并返回
"""

import SimpleITK as sitk
import os
import cv2
import numpy as np
from PIL import Image
import configparser


def dicom_metainfo(dicm_path, list_tag):
    '''
    获取dicom的元数据信息
    :param dicm_path: dicom文件地址
    :param list_tag: 标记名称列表,比如['0008|0018',]
    :return:
    '''
    reader = sitk.ImageFileReader()
    reader.LoadPrivateTagsOn()
    reader.SetFileName(dicm_path)
    reader.ReadImageInformation()
    return [reader.GetMetaData(t) for t in list_tag]


def dicom2array(dcm_path):
    '''
    读取dicom文件并把其转化为灰度图(np.array)
    https://simpleitk.readthedocs.io/en/master/link_DicomConvert_docs.html
    :param dcm_path: dicom文件
    :return:
    '''
    image_file_reader = sitk.ImageFileReader()
    image_file_reader.SetImageIO('GDCMImageIO')
    image_file_reader.SetFileName(dcm_path)
    image_file_reader.ReadImageInformation()
    image = image_file_reader.Execute()
    if image.GetNumberOfComponentsPerPixel() == 1:
        image = sitk.RescaleIntensity(image, 0, 255)
        if image_file_reader.GetMetaData('0028|0004').strip() == 'MONOCHROME1':
            image = sitk.InvertIntensity(image, maximum=255)
        image = sitk.Cast(image, sitk.sitkUInt8)
    img_x = sitk.GetArrayFromImage(image)[0]
    return img_x


def get_coord_list(result):
    """
    返回坐标点组成的列表， 并保存到文本文件中
    :return:
    """

    img_dir = result.index[0]  # 获取图片的地址
    print(img_dir)
    img_arr = dicom2array(img_dir)  # 获取具体的图片数据，二维数据
    tags = result[0][0]['train_data']['point']  # 获取图片的标签
    print("len of result: ", len(result))
    print("len of img_drr", len(img_dir))

    # 添加到列表
    annos, anno, temp = [], [], []  # annos存放坐标列表
    f = open("./coord.txt", "a")
    headline = 'path,identification,part,coord\n'
    f.writelines(headline)
    for i in range(len(result)):
        tags = result[i][0]['train_data']['point']
        index = result.index[i]
        anno = []
        for tag in tags:
            temp = []
            coords = tag['coord']
            identification = tag['tag']['identification']
            try:
                part = tag['tag']['vertebra']
            except:
                part = tag['tag']['disc']
            for coord in coords:
                temp.append(coord)
            anno.append(temp)

        text = index + "," + identification + "," + part + "," + str(anno)
        f.writelines(text)
        f.writelines("\n")
        print(anno)
        annos.append(anno)
    f.close()
    return annos



if __name__ == '__main__':
    dcm_path = r'../code/train/study1/image1.dcm'
    list_tag = ['0018|0015']
    r = dicom_metainfo(dcm_path, list_tag)
    print(r)
    # #
    import cv2

    src_dir = '../folder/train/study0'
    files = os.listdir(src_dir)
    i = 0

    for file in files:
        dcm_path = src_dir + "/" + file
        img_x = dicom2array(dcm_path)
        cv2.imshow('0', img_x)
        cv2.waitKey(0)
        cv2.imwrite("./temp_dir/dc/" + "image" + str(i) + ".png", img_x)
        i += 1

    cv2.waitKey(0)